package com.seashop.util;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

/**
 * @author moredln
 * @desc 日期工具类, 继承org.apache.commons.lang.time.DateUtils类
 * @date 2020-07-10 22:44
 */
public class DateUtil extends org.apache.commons.lang3.time.DateUtils {

	private static String[] parsePatterns = {
		"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
		"yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
		"yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

	/**
	 * 得到当前日期字符串 格式（yyyy-MM-dd）
	 */
	public static String getDate() {
		return getDate("yyyy-MM-dd");
	}

	/**
	 * 得到当前日期字符串 格式（yyyy-MM-dd） pattern可以为："yyyy-MM-dd" "HH:mm:ss" "E"
	 */
	public static String getDate(String pattern) {
		return DateFormatUtils.format(new Date(), pattern);
	}

	/**
	 * 得到日期字符串 默认格式（yyyy-MM-dd） pattern可以为："yyyy-MM-dd" "HH:mm:ss" "E"
	 */
	public static String formatDate(Date date, Object... pattern) {
		String formatDate = null;
		if (pattern != null && pattern.length > 0) {
			formatDate = DateFormatUtils.format(date, pattern[0].toString());
		} else {
			formatDate = DateFormatUtils.format(date, "yyyy-MM-dd");
		}
		return formatDate;
	}

	/**
	 * 得到日期时间字符串，转换格式（yyyy-MM-dd HH:mm:ss）
	 */
	public static String formatDateTime(Date date) {
		return formatDate(date, "yyyy-MM-dd HH:mm:ss");
	}

	/**
	 * 得到日期时间字符串，转换格式（yyyy-MM-dd HH:mm）
	 */
	public static String formatDateTimeBranch(Date date) {
		return formatDate(date, "yyyy-MM-dd HH:mm");
	}

	/**
	 * 得到当前时间字符串 格式（HH:mm:ss）
	 */
	public static String getTime() {
		return formatDate(new Date(), "HH:mm:ss");
	}

	/**
	 * 得到当前时间字符串 格式（HH:mm）
	 */
	public static String getTimeBranch() {
		return formatDate(new Date(), "HH:mm");
	}

	/**
	 * 得到当前日期和时间字符串 格式（yyyy-MM-dd HH:mm）
	 */
	public static String getDateTimeBranch() {
		return formatDate(new Date(), "yyyy-MM-dd HH:mm");
	}

	/**
	 * 得到当前日期和时间字符串 格式（yyyy-MM-dd HH:mm:ss）
	 */
	public static String getDateTime() {
		return formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
	}

	/**
	 * 得到当前年份字符串 格式（yyyy）
	 */
	public static String getYear() {
		return formatDate(new Date(), "yyyy");
	}

	/**
	 * 得到当前月份字符串 格式（MM）
	 */
	public static String getMonth() {
		return formatDate(new Date(), "MM");
	}

	/**
	 * 得到当天字符串 格式（dd）
	 */
	public static String getDay() {
		return formatDate(new Date(), "dd");
	}

	/**
	 * 得到当前星期字符串 格式（E）星期几
	 */
	public static String getWeek() {
		return formatDate(new Date(), "E");
	}

	/**
	 * 日期型字符串转化为日期 格式
	 * { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm",
	 *   "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm",
	 *   "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm" }
	 */
	public static Date parseDate(Object str) {
		if (str == null){
			return null;
		}
		try {
			return parseDate(str.toString(), parsePatterns);
		} catch (ParseException e) {
			return null;
		}
	}

	/**
	 * 日期型字符串转化为日期 格式
	 * { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm",
	 *   "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm",
	 *   "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm" }
	 */
	public static Date parseDates(Object str, String parrern) {
		if (str == null){
			return null;
		}
		try {
			return parseDate(str.toString(), parrern);
		} catch (ParseException e) {
			return null;
		}
	}

	/**
	 * 获取过去的天数
	 * @param date
	 * @return
	 */
	public static long pastDays(Date date) {
		long t = new Date().getTime()-date.getTime();
		return t/(24*60*60*1000);
	}

	/**
	 * 获取过去的小时
	 * @param date
	 * @return
	 */
	public static long pastHour(Date date) {
		long t = new Date().getTime()-date.getTime();
		return t/(60*60*1000);
	}

	/**
	 * 获取过去的分钟
	 * @param date
	 * @return
	 */
	public static long pastMinutes(Date date) {
		long t = new Date().getTime()-date.getTime();
		return t/(60*1000);
	}

	/**
	 * 转换为时间（天,时:分:秒.毫秒）
	 * @param timeMillis
	 * @return
	 */
    public static String formatDateTime(long timeMillis){
		long day = timeMillis/(24*60*60*1000);
		long hour = (timeMillis/(60*60*1000)-day*24);
		long min = ((timeMillis/(60*1000))-day*24*60-hour*60);
		long s = (timeMillis/1000-day*24*60*60-hour*60*60-min*60);
		long sss = (timeMillis-day*24*60*60*1000-hour*60*60*1000-min*60*1000-s*1000);
		return (day>0?day+",":"")+hour+":"+min+":"+s+"."+sss;
    }

	/**
	 * 获取两个日期之间的天数
	 *
	 * @param before
	 * @param after
	 * @return
	 */
	public static double getDistanceOfTwoDate(Date before, Date after) {
		long beforeTime = before.getTime();
		long afterTime = after.getTime();
		return (afterTime - beforeTime) / (1000 * 60 * 60 * 24);
	}

	/**
	 * 对比当前时间，大于返回TRUE，小于返回FALSE
	 * @return
	 */
	public static boolean compareDate(Date date){
		Date nowDate = new Date();
		return date.getTime()>nowDate.getTime();
	}

	/**
     * 获取现在时间
     */
    public static String getStringDate() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = formatter.format(currentTime);
        return dateString;
    }

    /**
     * 两个时间之间的天数
     */
    public static long getDays(String date1, String date2) {
        if (date1 == null || date1.equals(""))
            return 0;
        if (date2 == null || date2.equals(""))
            return 0;
        // 转换为标准时间
        SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        Date mydate = null;
        try {
            date = myFormatter.parse(date1);
            mydate = myFormatter.parse(date2);
        } catch (Exception e) {
        }
        long day = (date.getTime() - mydate.getTime()) / (24 * 60 * 60 * 1000);
        return Math.abs(day);
    }

	/**
	 * 两个时间之差
	 * @param startDate
	 * @param endDate
	 * @return 分钟
	 */
	public static Integer getBetweenMinutes(Date startDate, Date endDate) {
		Integer minutes = 0;
		try {
			if(startDate!=null&&endDate!=null) {
				long ss = 0;
				if(startDate.before(endDate)) {
					ss = endDate.getTime() - startDate.getTime();
				}else {
					ss = startDate.getTime() - endDate.getTime();
				}
				minutes = Integer.valueOf((int) (ss/(60*1000))) ;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return minutes;
	}
	/**
	 * 两个时间只差
	 * @param a
	 * @param b
	 * @return 分钟
	 */
	public static Integer getBetweenMinutes(String a, String b) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date startDate;
		Date endDate;
		try {
			startDate = format.parse(a);
			endDate = format.parse(b);
			try {
				long ss = 0;
				if(startDate.before(endDate)) {
					ss = endDate.getTime() - startDate.getTime();
				}else {
					ss = startDate.getTime() - endDate.getTime();
				}
				return Integer.valueOf((int) (ss/(60*1000))) ;
			} catch (Exception e) {
				e.printStackTrace();
				return 0;
			}
		} catch (ParseException e1) {
			e1.printStackTrace();
			return 0;
		}
	}
	/**
	 * 两个时间只差,
	 * 如果返回-1，则说明 endDate 在 startDate之前
	 * @param startDate
	 * @param endDate
	 * @return 秒数
	 */
	public static Integer getBetweenSecond(Date startDate, Date endDate) {
		Integer seconds = 0;
		try {
			if(startDate!=null&&endDate!=null) {
				long ss = 0;
				if(startDate.before(endDate)) {
					ss = endDate.getTime() - startDate.getTime();
				}else {
					ss = -1l;
				}
				seconds = Integer.valueOf((int) (ss/(1000))) ;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return seconds;
	}

	/**
	 * 两个时间只差
	 * @param a
	 * @param b
	 * @return 秒数
	 */
	public static Integer getBetweenSecond(String a, String b) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date startDate;
		Date endDate;
		try {
			startDate = format.parse(a);
			endDate = format.parse(b);
			try {
				long ss = 0;
				if(startDate.before(endDate)) {
					ss = endDate.getTime() - startDate.getTime();
				}else {
					ss = startDate.getTime() - endDate.getTime();
				}
				return Integer.valueOf((int) (ss/(1000))) ;
			} catch (Exception e) {
				e.printStackTrace();
				return 0;
			}
		} catch (ParseException e1) {
			e1.printStackTrace();
			return 0;
		}
	}
	public static String getDatFormat(Date date, String dateFormat) {
		try {
			SimpleDateFormat format = new SimpleDateFormat(dateFormat);
			return format.format(date);
		} catch (Exception e) {
			e.printStackTrace();
			SimpleDateFormat format = new SimpleDateFormat("YYYY-MM-DD");
			return format.format(new Date());
		}
	}

	/**
	 * 获取两个时间之间的日期、月份、年份
	 * @param startDate
	 * @param endDate
	 * @param type{1：日期，2：月份，其他：年份}
	 * @return
	 */
	public static List<String> getBetweenDates(String startDate, String endDate, Integer type) {
		SimpleDateFormat format= null;
		Date begin = null;
		Date end = null;
		Integer obj = null;
		Integer flag = null;
		if(type!=null&&type==1){
			format = new SimpleDateFormat("yyyy-MM-dd");
			obj = Calendar.DAY_OF_YEAR;
			flag = 9;
		}else if(type!=null&&type==2){
			format = new SimpleDateFormat("yyyy-MM");
			obj = Calendar.MONTH;
			flag = 11;
		}else{
			format = new SimpleDateFormat("yyyy");
			obj = Calendar.YEAR;
			flag = 9;
		}
		if(StringUtils.isNotEmpty(startDate)&& StringUtils.isNotEmpty(endDate)){
			try {
				begin = format.parse(startDate);
				end = format.parse(endDate);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}else{
			end = new Date();
			begin = getDateBefore(end,flag,obj);
		}

		List<String> result = new ArrayList<String>();
		Calendar tempStart = Calendar.getInstance();
		tempStart.setTime(begin);
		while (begin.getTime() <= end.getTime()) {
			result.add(format.format(tempStart.getTime()));
			tempStart.add(obj, 1);
			begin = tempStart.getTime();
		}
		return result;
	}
	/**
	 * 获取两个时间之间的日期、月份、年份
	 * @param date{YYYY-MM-DD-YYYY-MM-DD}
	 * @param type{1：日期，2：月份，其他：年份}
	 * @return
	 */
	public static List<String> getBetweenDates(String date,Integer type) {
		SimpleDateFormat format= null;
		Date begin = null;
		Date end = null;
		Integer obj = null;
		String startDate = null;
		String endDate = null;
		Integer flag = null;
		if(type!=null&&type==1){
			format = new SimpleDateFormat("yyyy-MM-dd");
			obj = Calendar.DAY_OF_YEAR;
			flag = 9;
		}else if(type!=null&&type==2){
			format = new SimpleDateFormat("yyyy-MM");
			obj = Calendar.MONTH;
			flag = 11;
		}else{
			format = new SimpleDateFormat("yyyy");
			obj = Calendar.YEAR;
			flag = 9;
		}
		if(StringUtils.isNotEmpty(date)){
			startDate = date.substring(0, 10);
			endDate = date.substring(date.length()-10, date.length());
			try {
				begin = format.parse(startDate);
				end = format.parse(endDate);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}else{
			end = new Date();
			begin = getDateBefore(end,flag,obj);
		}

		List<String> result = new ArrayList<String>();
		Calendar tempStart = Calendar.getInstance();
		tempStart.setTime(begin);
		while (begin.getTime() <= end.getTime()) {
			result.add(format.format(tempStart.getTime()));
			tempStart.add(obj, 1);
			begin = tempStart.getTime();
		}
		return result;
	}

	/**
	 * 拆分时间间隔
	 * Title: getDateArray
	 * Description: '2018-04-04 - 2018-05-22'
	 * @author lsx
	 * @date 2018年4月13日
	 */
	public static String[] getDateArray(String date) {
		String[] defalut = {"",""};
		try {
			if(StringUtils.isNotEmpty(date)) {
				String startDate = date.substring(0, 10);
				String endDate = date.substring(date.length()-10, date.length());
				String[] dates = {startDate,endDate};
				return dates;
			}else {
				return defalut;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return defalut;
		}
	}

	public static Date getDateBefore(Date d, int day,Integer type) {
		Calendar now = Calendar.getInstance();
		now.setTime(d);
		now.set(type, now.get(type) - day);
		return now.getTime();
	}

	/**
	 * 获取给定日期之前或之后的日期
	 * @param date
	 * @param type
	 * @param num
	 * @return
	 */
	public static String getPreviouslyDate(Date date, String type, Integer num) {

		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		String resultDate = "";
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		try {
			switch (type) {
				case "day":
					c.add(Calendar.DATE, num);
					break;
				case "month":
					c.add(Calendar.MONTH, num);
					break;
				case "year":
					c.add(Calendar.YEAR, num);
					break;
				default:
					c.add(Calendar.DATE, 0);
					break;
			}
			Date d = c.getTime();
			resultDate = format.format(d);
			return resultDate;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	/**
	 *******************************************
	 * 方法名称:判断日期是否是某一天
	 * 创建人：lsx
	 * 创建时间：2018年4月19日 下午9:44:57
	 * @param date
	 * @param num
	 * @return
	 * @return:boolean
	 *******************************************
	 */
	public static boolean isOneday(Date date, Integer num){
		SimpleDateFormat fmt=new SimpleDateFormat("yyyy-MM-dd");
		String dateStr = fmt.format(date).toString();
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new Date());
		calendar.add(Calendar.DAY_OF_MONTH, num);
		String oneDateStr = fmt.format(calendar.getTime()).toString();
		if(dateStr.equals(oneDateStr)){//格式化为相同格式
			return true;
		}else {
			return false;
		}
	}

	/**
	 * 将时间转为年月
	 * @param time
	 * @return
	 */
	public static String timeYears(String time){
		String stingtime = "";
		try {
			DateFormat dateFormat = new SimpleDateFormat("yyyy-MM");
			Date date = dateFormat.parse(time);
			stingtime = dateFormat.format(date).replace("-","/");
		}catch (Exception e){
			e.printStackTrace();
		}
		return stingtime;
	}

	/**
	 * 将时间转为年月日
	 * @param time
	 * @return
	 */
	public static String timeYears(String time, String parrern){
		String stingtime = "";
		try {
			DateFormat dateFormat = new SimpleDateFormat(parrern);
			Date date = dateFormat.parse(time);
			stingtime = dateFormat.format(date).replace("-","/");
		}catch (Exception e){
			e.printStackTrace();
		}
		return stingtime;
	}

	/**
	 * 获取时间段--30天
	 * @return
	 */
	public static Map getTimeSlot() {
		Map map = new HashMap();
		Calendar rightNow = Calendar.getInstance();
		rightNow.setTime(new Date());//获取当天时间
		String endTime = DateUtil.formatDate(rightNow.getTime(), "yyyy-MM-dd 23:59:59");
		String startTime = "";
		for(int i = 0; i < 29; i++){
			rightNow.add(Calendar.DAY_OF_YEAR,-1);
			startTime = DateUtil.formatDate(rightNow.getTime(), "yyyy-MM-dd 00:00:01");
		}
		map.put("startTime", startTime);
		map.put("endTime", endTime);
		return map;
	}

	/**
	 * 获取今天的开始及结束日期
	 * @return
	 */
	public static Map<String, Object> todayDate() {
		Map<String, Object> map = new HashMap<>();
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String stateTime = sdf.format(date)+" 00:00:01";
		String endTime = sdf.format(date)+" 23:59:59";
		map.put("startTime",stateTime);
		map.put("endTime",endTime);
		return map;
	}

	/**
	 * 获取时间段--30天
	 * @return
	 */
	public static Map getThreeTimeSlot() {
		Map map = new HashMap();
		Calendar rightNow = Calendar.getInstance();
		rightNow.setTime(new Date());//获取当天时间
		String endTime = DateUtil.formatDate(rightNow.getTime(), "yyyy-MM-dd 23:59:59");
		String startTime = "";
		for(int i = 0; i < 2; i++){
			rightNow.add(Calendar.DAY_OF_YEAR,-1);
			startTime = DateUtil.formatDate(rightNow.getTime(), "yyyy-MM-dd 00:00:01");
		}
		map.put("startTime", startTime);
		map.put("endTime", endTime);
		return map;
	}

	/**
     * 将时间戳转换为时间
     */
	public static String stampToDate(String s){
		String res;
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		long lt = new Long(s);
		Date date = new Date(lt);
		res = simpleDateFormat.format(date);
		return res;
	}

	/**
	 * 获取开始到结束时间
	 * @return
	 */
	public static Map getStartAndEndTimeSlot(int day) {
		Map map = new HashMap();
		Calendar rightNow = Calendar.getInstance();
		rightNow.setTime(new Date());//获取当天时间
		String endTime = DateUtil.formatDate(rightNow.getTime(), "yyyy-MM-dd 23:59:59");
		String startTime = "";
		for(int i = 0; i < day-1; i++){
			rightNow.add(Calendar.DAY_OF_YEAR,-1);
			startTime = DateUtil.formatDate(rightNow.getTime(), "yyyy-MM-dd 00:00:01");
		}
		map.put("startTime", startTime);
		map.put("endTime", endTime);
		return map;
	}

	/**
	 * 秒数转为时分秒
	 * @param time
	 * @return
	 */
	public static StringBuffer secondTurnTimeDivisionSecond(int time) {
		int temp = 0;
		StringBuffer sb=new StringBuffer();
		temp = time/3600;
		sb.append((temp<10)?"0"+temp+"时":""+temp+"时");

		temp=time%3600/60;
		sb.append((temp<10)?"0"+temp+"分":""+temp+"分");

		temp=time%3600%60;
		sb.append((temp<10)?"0"+temp:""+temp);
		return sb;
	}

	/**
	 * 秒数转为时分
	 * @param time
	 * @return
	 */
	public static StringBuffer secondTurnTimeDivision(int time) {
		int temp = 0;
		StringBuffer sb=new StringBuffer();
		temp = time/3600;
		sb.append((temp<10)?"0"+temp+"时":""+temp+"时");

		temp=time%3600/60;
		sb.append((temp<10)?"0"+temp+"分":""+temp+"分");

		return sb;
	}

	public static LocalDateTime dateCovertToLocalDateTime(Date date){
		Instant instant = date.toInstant();

		ZoneId zone = ZoneId.systemDefault();

		LocalDateTime nextretry = LocalDateTime.ofInstant(instant, zone);

		return nextretry;
	}
}
